package com.raos.caffeine.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * Caffeine配置类
 *
 * @author raos
 * @email 991207823@qq.com
 */
@EnableCaching
@Configuration
public class CaffeineConfig {

    public static final String ONE_CACHE_NAME = "oneCaffeineCache";

    /***
     * 配置缓存管理器
     * @return
     */
    @Bean(name = "caffeineCacheManager")
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(caffeineCacheBuilder());
        return cacheManager;
    }

    /***
     * caffeine缓存容器创建
     */
    private Caffeine<Object, Object> caffeineCacheBuilder() {
        return Caffeine.newBuilder()
                .maximumSize(1)
                .expireAfterWrite(30, TimeUnit.SECONDS);
    }

    @Bean(name = ONE_CACHE_NAME)
    public Cache<String, Object> oneCaffeineCache() {
        return Caffeine.newBuilder()
                .maximumSize(2)
                .expireAfterWrite(Duration.ofSeconds(30))
                .build();
    }

}
